<template>
  <div class="app-container">
    <!-- 搜索表单区域 -->
    <el-form
        :model="queryParams"
        ref="queryRef"
        :inline="true"
        v-show="showSearch"
        label-width="90px"
        class="flex-form"
    >
      <el-form-item label="员工姓名">
        <el-input
            v-model="queryParams.name"
            placeholder="请输入员工姓名"
            clearable
            @keyup.enter="handleQuery"
            max="20"
        />
      </el-form-item>

      <el-form-item label="员工工号">
        <el-input
            v-model="queryParams.employeeNumber"
            placeholder="请输入员工工号"
            clearable
            @keyup.enter="handleQuery"
            max="15"
        />
      </el-form-item>

      <el-form-item label="所属部门">
        <el-input
            v-model="queryParams.deptName"
            placeholder="请输入部门名称"
            clearable
            @keyup.enter="handleQuery"
            max="10"
        />
      </el-form-item>

      <el-form-item label="手机号码">
        <el-input
            v-model="queryParams.phone"
            placeholder="请输入手机号码"
            clearable
            @keyup.enter="handleQuery"
            max="11"
        />
      </el-form-item>

      <el-form-item label="职位">
        <el-input
            v-model="queryParams.positionName"
            placeholder="请输入职位"
            clearable
            @keyup.enter="handleQuery"
            max="10"
        />
      </el-form-item>

      <el-form-item label="身份证号">
        <el-input
            v-model="queryParams.idNumber"
            placeholder="请输入身份证号码"
            clearable
            @keyup.enter="handleQuery"
            max="18"
        />
      </el-form-item>

      <el-form-item class="form-actions">
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮区域 -->
    <el-row :gutter="12" class="action-buttons">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
      </el-col>
    </el-row>

    <!-- 表格区域 -->
    <el-table
        v-loading="loading"
        :data="employeeList"
        @selection-change="handleSelectionChange"
        stripe
        class="fixed-table"
    >
      <el-table-column type="selection" width="60" align="center" />

      <el-table-column label="头像" align="center" prop="avatar" width="80">
        <template #default="scope">
          <el-image
              style="width: 70px; height: 70px ; border-radius: 50% ; z-index: 10"
              :src="scope.row.avatar"
              :preview-src-list="[scope.row.avatar]"
              preview-teleported
          />
        </template>
      </el-table-column>

      <el-table-column label="员工姓名" align="center" prop="name" width="120" />
      <el-table-column label="员工工号" align="center" prop="employeeNumber" width="120" />

      <el-table-column label="所属部门" align="center" prop="deptName" width="220">
        <template #default="scope">
          <span>{{ scope.row.deptName }}</span>
        </template>
      </el-table-column>

      <el-table-column label="手机号码" align="center" prop="phone" width="130" />
      <el-table-column label="职位" align="center" prop="positionName" width="100" />

      <el-table-column label="员工类型" align="center" prop="type" width="100">
        <template #default="scope">
          <dict-tag :options="employee_status" :value="scope.row.status" />
        </template>
      </el-table-column>

      <el-table-column label="身份证号" align="center" prop="idNumber" width="180" />

      <el-table-column label="入职日期" align="center" prop="hireDate" width="140">
        <template #default="scope">
          <span>{{ parseTime(scope.row.hireDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="220">
        <template #default="scope">
          <router-link :to="'/employee/employee/employeeDetails/index/' + scope.row.id" class="link-type">
            <el-button type="text">查看详情</el-button>
          </router-link>
          <el-button type="text" @click="handleUpdate(scope.row)">修改</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 新增/修改对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="employeeRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="头像" :label-width="formLabelWidth">
          <el-upload
              class="avatar-uploader"
              action="http://localhost/dev-api/oss/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
          >
            <img v-if="avatar" :src="avatar" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>

        <el-form-item label="员工姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入员工姓名" max="20" />
        </el-form-item>

        <el-form-item label="员工工号" prop="employeeNumber">
          <el-input v-model="form.employeeNumber" placeholder="请输入员工工号" max="15" />
        </el-form-item>

        <el-form-item label="所属部门" prop="deptName">
          <el-input v-model="form.deptName" placeholder="请选择所属部门" max="10" />
        </el-form-item>

        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号码" max="11" />
        </el-form-item>

        <el-form-item label="职位" prop="positionName">
          <el-input v-model="form.positionName" placeholder="请选择职位" max="10" />
        </el-form-item>

        <el-form-item label="员工类型" prop="type">
          <el-select v-model="form.status">
            <el-option v-for="item in employee_status" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="身份证号" prop="idNumber">
          <el-input v-model="form.idNumber" placeholder="请输入身份证号码" max="18" />
        </el-form-item>

        <el-form-item label="入职日期" prop="hireDate">
          <el-date-picker
              clearable
              v-model="form.hireDate"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择入职日期"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Employee">
import { listEmployee, getEmployee, delEmployee, addEmployee, updateEmployee } from "@/api/employee/employee";
import {ElMessage} from "element-plus";

const { proxy } = getCurrentInstance();
const { employee_status, employee_type } = proxy.useDict("employee_status", "employee_type");

// 状态管理
const employeeList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    employeeNumber: null,
    deptName: null,
    phone: null,
    positionName: null,
    idNumber: null
  },
  rules: {
    name: [
      { required: true, message: "员工姓名不能为空", trigger: "blur" },
      { min: 2, max: 20, message: "姓名长度应为2-20个字符", trigger: "blur" },
    ],
    employeeNumber: [
      { required: true, message: "员工工号不能为空", trigger: "blur" },
      { max: 15, message: "工号长度不能超过15位", trigger: "blur" },
    ],
    phone: [
      { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号码", trigger: "blur" },
      { max: 11, message: "手机号码长度不正确", trigger: "blur" },
    ],
    idNumber: [
      {
        required: true,
        pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
        message: "请输入正确的身份证号码",
        trigger: "blur"
      },
      { max: 18, message: "身份证号码长度不正确", trigger: "blur" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

// 格式化时间
const parseTime = (time, format) => {
  if (!time) return "-";
  // 时间格式化逻辑（需引入dayjs或使用原生方法）
  return new Date(time).toISOString().split('T')[0];
};

/** 查询员工列表 */
function getList() {
  loading.value = true;
  listEmployee(queryParams.value).then(response => {
    employeeList.value = response.rows || [];
    total.value = response.total || 0;
    loading.value = false;
  }).catch(() => {
    loading.value = false;
    proxy.$modal.msgError("数据加载失败");
  });
}

/** 重置表单 */
function reset() {
  form.value = {
    name: null,
    employeeNumber: null,
    deptName: null,
    phone: null,
    positionName: null,
    idNumber: null
  };
  avatar.value = null;
  proxy.resetForm("employeeRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置搜索条件 */
function resetQuery() {
  // 修复：通过 $refs 访问表单实例并重置
  proxy.$refs.queryRef?.resetFields();
  // 确保所有查询参数被重置，并明确指定回到第一页
  Object.assign(queryParams.value, {
    pageNum: 1,
    pageSize: 10,
    name: null,
    employeeNumber: null,
    deptName: null,
    phone: null,
    positionName: null,
    idNumber: null,
  });
  handleQuery()
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增员工 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加员工";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  open.value = true;
  const _id = row.id;
  getEmployee(_id).then(response => {
    form.value = response.data;
    avatar.value = response.data.avatar;
    title.value = "修改员工";
  });
}

/** 提交表单 */
function submitForm() {
  form.value.avatar = avatar.value;
  proxy.$refs.employeeRef?.validate(valid => {
    if (valid) {
      const request = form.value.id ? updateEmployee : addEmployee;

      request(form.value).then(response => {
        proxy.$modal.msgSuccess(form.value.id ? "修改成功" : "新增成功");
        open.value = false;
        getList();
      }).catch(error => {
        proxy.$modal.msgError(error.message || "操作失败");
      });
    }
  });
}

/** 取消操作 */
function cancel() {
  open.value = false;
}

/** 删除员工 */
function handleDelete() {
  if (!ids.value.length) return proxy.$modal.msgWarning("请选择要删除的员工");

  proxy.$modal.confirm(`是否确认删除选中的 ${ids.value.length} 条数据？`).then(() => {
    return delEmployee(ids.value);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
    ids.value = [];
    single.value = true;
    multiple.value = true;
  }).catch(() => {});
}

/** 导出数据 */
function handleExport() {
  proxy.download('employee/employee/export', {
    ...queryParams.value
  }, `employee_${new Date().getTime()}.xlsx`);
}

/*头像上传*/
const avatar = ref(null);
const handleAvatarSuccess = (res, file) => {
  if (res.code === 200) {
    console.log(res)
    avatar.value = res.data;
    ElMessage.success("头像上传成功");
  } else {
    ElMessage.error(res.msg);
  }
};
const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}

// 初始化加载
getList();
</script>

<style scoped>
/* 弹性布局表单 */
.flex-form {
  display: flex;
  flex-wrap: wrap;
  gap: 24px;
  padding: 24px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.05);
}

.el-form-item {
  flex-basis: calc(25% - 24px); /* 每行4个输入框 */
  min-width: 280px;
  max-width: 100%;
  margin-bottom: 0;
}

/* 搜索按钮单独一行 */
.form-actions {
  flex-basis: 100%;
  display: flex;
  gap: 12px;
  margin-top: 8px;
}

@media (max-width: 1440px) {
  .flex-form .el-form-item {
    flex-basis: calc(33.33% - 24px); /* 每行3个输入框 */
  }
}

@media (max-width: 1024px) {
  .flex-form .el-form-item {
    flex-basis: calc(50% - 24px); /* 每行2个输入框 */
  }
}

@media (max-width: 768px) {
  .flex-form .el-form-item {
    flex-basis: 100%; /* 每行1个输入框 */
  }
}

/* 输入框样式优化 */
.el-input__inner {
  height: 40px;
  line-height: 40px;
  border-radius: 8px;
  padding: 0 14px;
  white-space: nowrap; /* 禁止换行 */
  overflow: hidden;
  text-overflow: ellipsis; /* 超出显示省略号 */
}

/* 表格样式优化 */
.fixed-table {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.05);
}

.fixed-table th {
  background: #f7f8fa;
  color: #303133;
  font-weight: 500;
  padding: 14px 0;
  white-space: nowrap;
}

.fixed-table td {
  padding: 14px 0;
  white-space: nowrap;
}

.fixed-table .cell {
  padding: 0 16px;
  line-height: 24px;
  overflow: hidden;
  text-overflow: ellipsis;
}

.avatar-img {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  object-fit: cover;
  border: 1px solid #ebeef5;
}

/* 操作按钮区域 */
.action-buttons {
  margin: 24px 0;
}

.el-button {
  border-radius: 8px;
  padding: 9px 16px;
  transition: all 0.2s;
}

.el-button:hover {
  transform: translateY(-1px);
}

/* 分页组件 */
.pagination {
  margin-top: 24px;
  text-align: right;
}

/* 对话框 */
.el-dialog {
  border-radius: 12px;
  overflow: hidden;
}

.el-dialog__header {
  background: #f7f8fa;
  padding: 18px 24px;
  border-bottom: 1px solid #ebeef5;
}

.el-dialog__title {
  font-size: 18px;
  font-weight: 500;
  color: #303133;
}

.el-dialog__body {
  padding: 24px;
}

.el-dialog__footer {
  padding: 16px 24px;
  border-top: 1px solid #ebeef5;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式布局 */
@media (max-width: 1200px) {
  .app-container {
    padding: 16px;
  }
}

@media (max-width: 768px) {
  .fixed-table th,
  .fixed-table td {
    padding: 10px 0;
    font-size: 14px;
  }
}

/*头像样式*/
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>